//
//  AppDelegate.m
//  DDMusic
//
//  Created by rimi on 16/11/4.
//  Copyright © 2016年 FengBaoFamily. All rights reserved.
//

#import "AppDelegate.h"
#import "DDLauchViewController.h"
#import <AVOSCloud.h>
#import "DDNetWorkTools.h"
#import "DDPublicMacro.h"
#import "DDAppLauchViewController.h"
#import <AVOSCloudSNS.h>
#import <AVFoundation/AVFoundation.h>
#import "DDMainMusicCellViewModel.h"
@interface AppDelegate ()
@property (nonatomic,strong) DDMainMusicCellViewModel* viewModel;//用于提前请求主页面数据的视图模型属性
@property (nonatomic,strong) DDAppLauchViewController* appLauchViewController;//第一次加载app的页面
@property (nonatomic,strong) DDLauchViewController* lauchViewController;//加载app的页面
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#pragma mark数据存储
    [self leanCloudWithlaunchOptions:launchOptions];
    [self loadMainVcData];
    //   [self loadLauchData];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.windowLevel = UIWindowLevelNormal;
    
#pragma mark根据是否是第一次进入app来选择跳转哪一个控制器
    if ([[NSUserDefaults standardUserDefaults]valueForKey:ISFIRSTLOGINAPP] == nil) {
        self.appLauchViewController = [[DDAppLauchViewController alloc]init];
        self.window.rootViewController = self.appLauchViewController;
        [self.window makeKeyAndVisible];
        [[NSUserDefaults standardUserDefaults]setObject:@"isFirstLoginApp" forKey:ISFIRSTLOGINAPP];
    }else{
        self.lauchViewController  = [[DDLauchViewController alloc]init];
        self.window.rootViewController = self.lauchViewController;
        [self.window makeKeyAndVisible];
    }
    
    
    
    
    
    
    
    return YES;
}

#pragma mark LeanCloud数据储存
- (void)leanCloudWithlaunchOptions:(NSDictionary*)launchOptions{
    [AVOSCloud setApplicationId:@"U60y8vLPWS2FSAIPexv1ihxn-gzGzoHsz" clientKey:@"GsBAv8K1G5GdXaVt3RO9ditC"];
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    
    
}
#pragma mark 下载启动页面数据方法
- (void)loadLauchData{
    AVQuery* query = [AVQuery queryWithClassName:@"LauchData"];
    [query getObjectInBackgroundWithId:@"581c50f20ce46300587a0ce3" block:^(AVObject *object, NSError *error) {
        NSString* isRefresh = [object objectForKey:@"LaunchRecommendMusicIsRefresh"];
        
        if ([isRefresh isEqualToString:@"YES"]) {
            [query getObjectInBackgroundWithId:@"581cad2b8ac247004fe8c89e" block:^(AVObject *object, NSError *error) {
                NSNumber* beginTime = [object valueForKey:@"MusciBeginTime"];
                [[NSUserDefaults standardUserDefaults]setObject:beginTime forKey:LAUNCHMUSICBEGINTIME];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }];
            [query getObjectInBackgroundWithId:@"581cad58a22b9d0067ba4e8d" block:^(AVObject *object, NSError *error) {
                NSNumber* continueTime = [object valueForKey:@"MusciContinueTime"];
                [[NSUserDefaults standardUserDefaults]setObject:continueTime forKey:LAUNCHMUSICCONTINUTIME];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }];
            [query getObjectInBackgroundWithId:@"581c2099a22b9d0067b4f1e8" block:^(AVObject *object, NSError *error) {
                NSString* imageUrl = [object objectForKey:@"LaunchRecommendMusicImage"];
                NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
                AFURLSessionManager* manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
                NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
                NSURLSessionDownloadTask* downLoadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                    NSURL* downLoadUrl = [[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",[response suggestedFilename]] forKey:LAUNCHMUSICIMAGENAME];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    return [downLoadUrl URLByAppendingPathComponent:[response suggestedFilename]];
                    
                } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                    
                    
                }];
                [downLoadTask resume];
            }];
            [query getObjectInBackgroundWithId:@"581c2b6f67f35600588c1dba" block:^(AVObject *object, NSError *error) {
                NSString* imageUrl = [object objectForKey:@"LaunchRecommendMusicUrl"];
                NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
                AFURLSessionManager* manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
                NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
                NSURLSessionDownloadTask* downLoadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                    NSURL* downLoadUrl = [[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",[response suggestedFilename]] forKey:LAUNCHMUSICURLNAME];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    return [downLoadUrl URLByAppendingPathComponent:[response suggestedFilename]];
                } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                    NSLog(@"%@",filePath);
                    
                }];
                [downLoadTask resume];
            }];
            
        }
    }];
    
}
#pragma mark 提前请求主页面的数据
- (void)loadMainVcData{
    [self.viewModel loadDataWithStyle:HotMusicDataStyle isOK:^(BOOL isOk, NSError *error) {
        NSLog(@"%d %@",isOk,error);
        if (isOk) {
            if ([[NSUserDefaults standardUserDefaults]valueForKey:ISFIRSTLOGINAPP] == nil) {
                self.appLauchViewController.viewModel = self.viewModel;
            }else{
                self.lauchViewController.viewModel = self.viewModel;
            }
        }
        [self.viewModel loadDataWithStyle:RecommendMusicDataStyle isOK:^(BOOL isOk, NSError *error) {
            if (isOk) {
                if ([[NSUserDefaults standardUserDefaults]valueForKey:ISFIRSTLOGINAPP] == nil) {
                    self.appLauchViewController.viewModel = self.viewModel;
                    NSLog(@"%@",self.appLauchViewController.viewModel);
                }else{
                    self.lauchViewController.viewModel = self.viewModel;
                    NSLog(@"%@",self.lauchViewController.viewModel);
                }
                
            }
        }];
    }];
    
    
    
}
#pragma mark 第三方登录
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [AVOSCloudSNS handleOpenURL:url];
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [AVOSCloudSNS handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    return [AVOSCloudSNS handleOpenURL:url];
}


- (void)applicationWillResignActive:(UIApplication *)application {
#pragma mark  设置音频后台播放
    //1,在plist文件增加Required background modes 这个key 并在该key值下添加一个App plays audio or streams audio/video using AirPlay 值
    //2,下面这些代码
    AVAudioSession* audioSession = [AVAudioSession sharedInstance];
    [audioSession  setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
}


@end
